<?php

defined('BASEPATH') or die('forbidden');

/**
 * 辅助函数
 * @author  Karson
 * @name    function.php
 * @since   2013-4-8 13:46:01
 */

/**
 * 获取配置选项
 * @param string $item
 * @return string
 */
function get_config_item($item) {
    $framework = &get_instance('controller');
    $result = $framework->cache->get("config_item_{$item}");
    if (!$result) {
        $one = $framework->db->one("SELECT * FROM {pre}config WHERE name='{$item}'");
        $result = is_array($one) ? $one['content'] : '';
        $framework->cache->set("config_item_{$item}", $result);
    }
    return $result;
}

function get_full_url($url) {
    $url = substr($url, 0, 4) != 'http' ? 'http://' . $url : $url;
    return $url;
}

/**
 * 判断会员权限 
 */
function check_user_level($rank = 1, $catalog = null, $action = null) {
    $c = 0;
    $r = '';
    $framework = &get_instance('controller');
    if (!$framework->auth->is_login()) {
        $r = '未登录';
    } else {
        if (!$framework->auth->check_level($rank, $catalog, $action)) {
            $r = '权限不足';
        } else {
            return true;
        }
    }
    json_output($c, $r);
}

/**
 * 更新会员基础表信息
 * @param mixed $fields 更新的字段信息
 * @param int $user_id 会员ID,默认为当前登录会员
 * @return boolean 
 */
function user_basic($fields = array(), $user_id = null) {
    $set = '';
    if (is_array($fields)) {
        foreach ($fields as $field => $data) {
            $set[] = "`" . $field . "` = '" . $data . "' ";
        }
        $set = implode(' , ', $set);
    } else {
        $set = $fields;
    }
    $framework = &get_instance('controller');
    $user_id = is_null($user_id) ? $framework->auth->user_id : $user_id;
    $framework->db->query("UPDATE {pre}user SET {$set} WHERE id='{$user_id}'");
    if ($framework->db->affected_rows()) {
        if ($user_id == $framework->auth->user_id) {
            $framework->auth->fields = array_merge($framework->auth->fields, $fields);
        }
        unset($one);
        return true;
    } else {
        return false;
    }
}

/**
 * 更新会员扩展表信息
 * @param mixed $fields 更新的字段信息
 * @param int $user_id 会员ID,默认为当前登录会员
 * @return boolean 
 */
function user_extension($fields = array(), $user_id = null) {
    $set = '';
    if (is_array($fields)) {
        foreach ($fields as $field => $data) {
            $set[] = "`" . $field . "` = '" . $data . "' ";
        }
        $set = implode(' , ', $set);
    } else {
        $set = $fields;
    }
    $framework = &get_instance('controller');
    $user_id = is_null($user_id) ? $framework->auth->user_id : $user_id;
    $framework->db->query("UPDATE {pre}user_extension SET {$set} WHERE user_id='{$user_id}'");
    if ($framework->db->affected_rows()) {
        if ($user_id == $framework->auth->user_id) {
            $framework->auth->fields = array_merge($framework->auth->fields, $fields);
        }
        unset($one);
        return true;
    } else {
        return false;
    }
}

/**
 * 增减用户统计/通知FLASH
 * @param array $fields array('field'=>'value');
 * @param int $user_id 会员ID
 * @return boolean
 */
function user_count($fields = array(), $user_id = null) {
    if (is_array($fields)) {
        $temp = array();
        foreach ($fields as $m => $n) {
            $temp[] = "`{$m}`=`{$m}`+{$n}";
        }
        $set = implode(',', $temp);
    } else {
        $set = $fields;
        $fields = array($fields);
    }
    $fields = array_filter($fields);
    $framework = &get_instance('controller');
    $user_id = is_null($user_id) ? $framework->auth->user_id : $user_id;
    //读取会员统计信息,如果是当前会员则不再读取数据库的数据
    if ($framework->auth->is_login() && $user_id == $framework->auth->user_id) {
        $one = $framework->auth->fields;
    } else {
        $one = $framework->db->one("SELECT * FROM {pre}user_count WHERE user_id='{$user_id}'");
        unset($one['user_id']);
    }
    if (is_array($one)) {
        $framework->db->query("UPDATE {pre}user_count SET {$set} WHERE user_id='{$user_id}'");
        if ($framework->db->affected_rows()) {
            //将数据先增加
            foreach ($fields as $m => $n) {
                isset($one[$m]) && $one[$m] += $n;
            }
            //更新了的字段数据
            $update = array_intersect_key($one, $fields);
            if ($user_id == $framework->auth->user_id) {
                $framework->auth->fields = array_merge($framework->auth->fields, $update);
            }
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
 * 记录邀请信息
 */
function invite($user_id) {
    $framework = &get_instance('controller');
    $row = $framework->db->one("SELECT * FROM {pre}user WHERE id='{$user_id}'");
    $invite = $framework->cookie->get("invite");
    $invite_user_id = $framework->cookie->get("invite_user_id");
    $invite_user_name = $framework->cookie->get("invite_user_name");
    //如果邀请人同被邀请人
    if ($invite_user_id == $user_id)
        return false;
    if (is_array($row) && $invite == 'open' && $invite_user_id != '' && $invite_user_name != '') {
        //判断当天是否同一IP多次注册
        $time = time();
        $row = $this->db->one("SELECT COUNT(*) AS num FROM {pre}user WHERE joinip='{$ip}' AND {$time}-jointime<86400");
        if (is_array($row) && $row['num'] > 1)
            return false;
        //插入邀请记录
        $framework->db->simple("INSERT into {pre}invite(user_id,username,invite_id,invite_username,ip,referer,createtime,state)
                                VALUES({$invite_user_id},'{$invite_user_name}',{$user_id},'{$row['username']}','{$row['joinip']}','{$row['referer']}',{$row['jointime']},0)");
        //增加积分
        scores($framework->config['scores']['invite_register'], $invite_user_id, "通过邀请链接注册");
        //增加会员统计计数
        user_count(array('invites' => 1), $invite_user_id);
        //发送站内短消息通知
        $title = "又有新的朋友通过您的邀请链接加入一号券";
        $content = "亲爱的{$invite_user_name}:<br />您好！{$row['username']}于" . date("Y-m-d H:i:s", $row['jointime']) . "通过您发送的邀请链接成功加入一号券，为感谢您对一号券的支持，一号券为您增加了{$framework->config['scores']['invite_register']}积分。再次感谢您对一号券的支持！<br />一号券";
        send_note($title, $content, $invite_user_id);
        $framework->cookie->set("invite", "register");
    }
}

/**
 * 系统发送站内短信
 * @param string $content 短信内容
 * @param int $user_id 接收会员ID
 * @param string $type 短信类型
 * @return bool
 */
function send_note($content, $user_id, $type = 'system') {
    if ($content == '' || intval($user_id) <= 0)
        return false;
    $content = addslashes($content);
    $framework = &get_instance('controller');
    $data = array('from_id' => 1, 'user_id' => $user_id, 'type' => $type, 'content' => $content, 'createtime' => time());
    if ($framework->db->insert('{pre}note', $data)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 发送Email
 * @param string $title 主题
 * @param string $content 邮件内容
 * @param string $to 收件人
 * @return bool
 */
function send_email($title, $content, $to, $template = 'default') {
    $framework = &get_instance('controller');
    if ($template) {
        $template = file_get_contents(UPLOADPATH . "email/{$template}.html");
        if ($template) {
            $content = str_replace('{content}', $content, str_replace('{title}', $title, $template));
            $content = str_replace('{siteurl}', base_url(1), str_replace('{sitename}', $framework->config['sitename'], $content));
        }
    }
    $framework->load->library("email");
    $framework->email->to($to);
    $framework->email->subject($title);
    $framework->email->message($content);
    return $framework->email->send();
}

/**
 * 用户积分增减
 * @param int $score 增加的分值，可正可负
 * @param int $user_id 操作的用户ID，为0时代表当前登录用户
 * @param int $reason 操作原因
 * @param int $operator 操作人
 * @return int
 */
function scores($scores = 0, $user_id = 0, $reason = 'unknown', $operator = 'system') {
    if (!$scores)
        return 0;
    $framework = get_instance('controller');
    $user_id = !$user_id ? $framework->auth->user_id : $user_id;
    $time = time();
    $ip = get_ip();
    user_count(array('scores' => $scores), $user_id);
    $framework->db->query("INSERT INTO {pre}scores(user_id,scores,reason,operator,createtime,ip) VALUES('{$user_id}','{$scores}','{$reason}','{$operator}','{$time}','{$ip}')");
    return true;
}

/**
 * 获取会员的主页地址
 * @param int $id 会员ID
 * @param string $personal 会员个性化主页
 * @param boolean $full 是否绝对路径
 * @return string
 */
function get_user_url($id, $personal = '', $full = false) {
    $personal = $personal == '' ? $id : $personal;
    return site_url("/user/{$personal}/", $full);
}

/**
 * 获取会员头像
 * @param int $user_id 会员ID
 * @param string $face 头像位置值
 * @param int $size 头像大小
 * @return string
 */
function get_user_face($user_id = 0, $face = '', $size = 50) {
    if (substr($face, 0, 7) == 'http://') {
        $size = $size == 160 ? 180 : $size;
        return str_replace('/50/', '/' . $size . '/', $face);
    } else if ($face == '') {
        return "/res/images/common/face{$size}.gif";
    } else {
        return "/uploads/face/{$user_id}/{$size}.jpg";
    }
}

/**
 * 获取会员年龄
 * @param int $birthday 会员生日
 * @param string $suffix 附加值
 * @return string
 */
function get_user_age($birthday, $suffix = "岁") {
    return !$birthday ? '' : (date("Y") - date("Y", $birthday)) . $suffix;
}

/**
 * 获取会员地域
 * @param int $location 会员地域
 * @param string $suffix 附加值
 * @return string
 */
function get_user_location($location, $prefix = "来自") {
    return $location == '' ? '' : $prefix . $location;
}